<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动漫数据管理工具</title>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .tag {
            display: inline-flex;
            align-items: center;
            background-color: #E5E7EB;
            border-radius: 9999px;
            padding: 0.25rem 0.75rem;
            margin: 0.25rem;
            font-size: 0.875rem;
        }
        .tag-remove {
            margin-left: 0.5rem;
            cursor: pointer;
            color: #6B7280;
        }
        .tag-remove:hover {
            color: #EF4444;
        }
        .season-card {
            border: 1px solid #E5E7EB;
            border-radius: 0.5rem;
            padding: 1rem;
            margin-bottom: 1rem;
            position: relative;
        }
        .remove-season {
            position: absolute;
            top: 0.5rem;
            right: 0.5rem;
            color: #EF4444;
            cursor: pointer;
        }
        .json-container {
            background-color: #1F2937;
            color: #E5E7EB;
            border-radius: 0.5rem;
            padding: 1rem;
            max-height: 400px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 0.875rem;
            white-space: pre-wrap;
        }
        .notification {
            position: fixed;
            top: 1rem;
            right: 1rem;
            padding: 1rem;
            border-radius: 0.5rem;
            color: white;
            opacity: 0;
            transform: translateY(-1rem);
            transition: all 0.3s ease;
            z-index: 100;
        }
        .notification.show {
            opacity: 1;
            transform: translateY(0);
        }
        .notification.success {
            background-color: #10B981;
        }
        .notification.error {
            background-color: #EF4444;
        }
        .image-input-group {
            display: flex;
            gap: 0.5rem;
        }
        .image-input-group input[type="text"] {
            flex-grow: 1;
        }
        .image-input-group select {
            width: 100px;
        }
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 0.5rem;
            margin-top: 1rem;
        }
        .pagination button {
            padding: 0.25rem 0.75rem;
            border-radius: 0.25rem;
            border: 1px solid #ddd;
            background-color: white;
            cursor: pointer;
        }
        .pagination button.active {
            background-color: #3B82F6;
            color: white;
            border-color: #3B82F6;
        }
        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .search-container {
            margin-bottom: 1rem;
            display: flex;
            gap: 0.5rem;
        }
        .search-container input {
            flex-grow: 1;
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 0.25rem;
        }
        .search-container button {
            background-color: #3B82F6;
            color: white;
            border: none;
            padding: 0 1rem;
            border-radius: 0.25rem;
            cursor: pointer;
        }
        .search-container button:hover {
            background-color: #2563EB;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- 顶部导航 -->
	<a href="https://uutool.cn/baike-img/" target="_blank">baidu链接转化</a>
	<a href="https://www.anibk.com/" target="_blank">动漫查询</a>
	<a href="https://movie.douban.com/" target="_blank">豆瓣</a>
	
	
    <nav class="bg-white shadow-sm">
        <div class="container mx-auto px-4 py-3">
            <div class="flex justify-between items-center">
                <h1 class="text-xl font-bold text-gray-800">
                    <i class="fa fa-film text-blue-500 mr-2"></i>动漫数据管理工具
                </h1>
                <div class="flex space-x-2">
                    <button id="export-btn" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md text-sm">
                        <i class="fa fa-download mr-1"></i>导出JSON
                    </button>
                    <button id="import-btn" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md text-sm">
                        <i class="fa fa-upload mr-1"></i>导入JSON
                    </button>
                    <button id="clear-btn" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-md text-sm">
                        <i class="fa fa-trash mr-1"></i>清除数据
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <div class="container mx-auto px-4 py-6">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- 左侧表单 -->
            <div class="bg-white rounded-lg shadow-sm p-6">
                <h2 class="text-lg font-medium text-gray-800 mb-4">添加/编辑动漫</h2>
                
                <form id="anime-form" class="space-y-4">
                    <!-- 基本信息 -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">ID</label>
                            <input type="number" name="id" required readonly
                                class="w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <p class="text-xs text-gray-500 mt-1">ID将自动生成</p>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">标题</label>
                            <input type="text" name="title" required 
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">图片路径</label>
                        <div class="image-input-group">
                            <input type="text" name="image" 
                                class="px-3 py-2 border border-gray-300 rounded-l-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                placeholder="输入图片文件名（不含路径和扩展名）">
                            <select name="image-format" class="px-3 py-2 border border-gray-300 rounded-r-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="webp">webp</option>
                                <option value="jpg">jpg</option>
                                <option value="png">png</option>
                                <option value="jpeg">jpeg</option>
                                <option value="gif">gif</option>
                            </select>
                        </div>
                        <p class="text-xs text-gray-500 mt-1">实际路径为：./images/文件名.扩展名</p>
                    </div>
                    
                    <!-- 标签管理 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">标签</label>
                        <div class="flex">
                            <input type="text" id="tag-input" 
                                class="flex-grow px-3 py-2 border border-gray-300 rounded-l-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                                placeholder="输入标签，可用逗号或顿号分隔">
                            <button type="button" id="add-tag-btn" class="bg-blue-500 text-white px-4 py-2 rounded-r-md">
                                <i class="fa fa-plus"></i>
                            </button>
                        </div>
                        <div id="tags-container" class="mt-2 flex flex-wrap"></div>
                    </div>
                    
                    <!-- 状态和评分 -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                            <select name="status" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="已看完">已看完</option>
                                <option value="部分观看">部分观看</option>
                                <option value="未看">未看</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">评分</label>
                            <input type="number" name="star" min="0" max="5" step="0.1" 
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">导演</label>
                        <input type="text" name="director" 
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div class="flex items-center">
                        <input type="checkbox" name="favorite" id="favorite" class="mr-2">
                        <label for="favorite" class="text-sm font-medium text-gray-700">添加到收藏</label>
                    </div>
                    
                    <!-- 季/季节信息 -->
                    <div>
                        <div class="flex justify-between items-center mb-2">
                            <label class="block text-sm font-medium text-gray-700">季/季节信息</label>
                            <button type="button" id="add-season-btn" class="text-blue-500 text-sm">
                                <i class="fa fa-plus mr-1"></i>添加季
                            </button>
                        </div>
                        
                        <div id="seasons-container">
                            <!-- 季信息将通过JS动态添加 -->
                        </div>
                    </div>
                    
                    <button type="submit" class="w-full bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded-md">
                        <i class="fa fa-save mr-1"></i>保存数据
                    </button>
                </form>
            </div>
            
            <!-- 右侧搜索和列表 -->
            <div class="bg-white rounded-lg shadow-sm p-6">
                <h2 class="text-lg font-medium text-gray-800 mb-4">动漫列表</h2>
                
                <!-- 搜索框 -->
                <div class="search-container">
                    <input type="text" id="search-input" placeholder="搜索名称或ID...">
                    <button id="search-btn" class="flex items-center">
                        <i class="fa fa-search mr-1"></i>搜索
                    </button>
                    <button id="clear-search-btn" class="bg-gray-200 hover:bg-gray-300">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
                
                <!-- 动漫列表 -->
                <div id="anime-list" class="space-y-4">
                    {/* 动漫列表将通过JS动态添加 */}
                </div>
                
                <!-- 分页控件 -->
                <div id="pagination" class="pagination">
                    {/* 分页按钮将通过JS动态添加 */}
                </div>
            </div>
        </div>
        
        <!-- JSON预览 -->
        <div class="bg-white rounded-lg shadow-sm p-6 mt-6">
            <h2 class="text-lg font-medium text-gray-800 mb-4">JSON预览</h2>
            <div class="json-container" id="json-preview">
                {/* JSON内容将在这里显示 */}
            </div>
            
            <div class="mt-4 flex space-x-2">
                <button id="copy-json-btn" class="bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded-md text-sm flex-1">
                    <i class="fa fa-copy mr-1"></i>复制JSON
                </button>
                <button id="save-local-btn" class="bg-purple-500 hover:bg-purple-600 text-white px-4 py-2 rounded-md text-sm flex-1">
                    <i class="fa fa-save mr-1"></i>保存到本地
                </button>
            </div>
        </div>
    </div>
    
    <!-- 通知 -->
    <div id="notification" class="notification"></div>
    
    <!-- 文件导入输入 -->
    <input type="file" id="import-file" accept=".json" class="hidden">
    
    <script>
        // 全局变量
        let animeData = [];
        let currentTags = [];
        let currentEditIndex = -1; // 记录当前编辑的索引，-1表示新增
        
        // 分页和搜索相关变量
        let currentPage = 1;
        let itemsPerPage = 7; // 每页显示5条数据
        let searchTerm = '';
        
        // DOM元素
        const animeForm = document.getElementById('anime-form');
        const tagInput = document.getElementById('tag-input');
        const addTagBtn = document.getElementById('add-tag-btn');
        const tagsContainer = document.getElementById('tags-container');
        const seasonsContainer = document.getElementById('seasons-container');
        const addSeasonBtn = document.getElementById('add-season-btn');
        const jsonPreview = document.getElementById('json-preview');
        const copyJsonBtn = document.getElementById('copy-json-btn');
        const saveLocalBtn = document.getElementById('save-local-btn');
        const exportBtn = document.getElementById('export-btn');
        const importBtn = document.getElementById('import-btn');
        const importFile = document.getElementById('import-file');
        const clearBtn = document.getElementById('clear-btn');
        const animeList = document.getElementById('anime-list');
        const notification = document.getElementById('notification');
        const idInput = document.querySelector('input[name="id"]');
        const searchInput = document.getElementById('search-input');
        const searchBtn = document.getElementById('search-btn');
        const clearSearchBtn = document.getElementById('clear-search-btn');
        const paginationContainer = document.getElementById('pagination');
        
        // 初始化
        document.addEventListener('DOMContentLoaded', async function() {
            // 先从本地存储加载数据
            loadFromLocalStorage();
            
            // 若本地存储无数据，尝试从JSON文件加载
            if (animeData.length === 0) {
                try {
                    const response = await fetch('anime-data.json');
                    if (response.ok) {
                        const fileData = await response.json();
                        if (Array.isArray(fileData)) {
                            animeData = fileData;
                            showNotification('已从文件加载初始数据', 'success');
                        }
                    }
                } catch (err) {
                    console.error('从JSON文件加载数据失败:', err);
                    showNotification('加载初始数据文件失败', 'error');
                }
            }
            
            // 设置自增ID
            setAutoIncrementId();
            
            // 添加第一个季
            addSeason();
            
            // 绑定事件
            bindEvents();
            
            // 更新预览
            updateJsonPreview();
            updateAnimeList();
        });
        
        // 绑定事件
        function bindEvents() {
            // 添加标签
            addTagBtn.addEventListener('click', addTag);
            tagInput.addEventListener('keypress', function(e) {
                // 支持回车、逗号、顿号添加标签
                if (e.key === 'Enter' || e.key === ',' || e.key === '、') {
                    e.preventDefault();
                    addTag();
                }
            });
            
            // 添加季
            addSeasonBtn.addEventListener('click', function() {
                addSeason();
            });
            
            // 表单提交
            animeForm.addEventListener('submit', function(e) {
                e.preventDefault();
                saveAnime();
            });
            
            // JSON操作
            copyJsonBtn.addEventListener('click', copyJsonToClipboard);
            saveLocalBtn.addEventListener('click', saveToLocalStorage);
            exportBtn.addEventListener('click', exportJson);
            importBtn.addEventListener('click', function() {
                importFile.click();
            });
            importFile.addEventListener('change', importJson);
            clearBtn.addEventListener('click', clearData);
            
            // 搜索功能
            searchBtn.addEventListener('click', performSearch);
            searchInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    performSearch();
                }
            });
            clearSearchBtn.addEventListener('click', clearSearch);
        }
        
        // 执行搜索
        function performSearch() {
            searchTerm = searchInput.value.trim();
            currentPage = 1; // 搜索后重置到第一页
            updateAnimeList();
        }
        
        // 清除搜索
        function clearSearch() {
            searchInput.value = '';
            searchTerm = '';
            currentPage = 1; // 清除搜索后重置到第一页
            updateAnimeList();
        }
        
        // 设置自增ID
        function setAutoIncrementId() {
            if (animeData.length === 0) {
                idInput.value = 1;
                return;
            }
            
            // 找到最大ID并加1
            const maxId = Math.max(...animeData.map(anime => anime.id));
            idInput.value = maxId + 1;
        }
        
        // 添加标签 - 支持逗号和顿号分隔
        function addTag() {
            const tagValue = tagInput.value.trim();
            if (!tagValue) return;
            
            // 使用逗号或顿号分割标签
            const tags = tagValue.split(/[,、]/).map(tag => tag.trim()).filter(tag => tag);
            
            tags.forEach(tag => {
                if (!currentTags.includes(tag)) {
                    currentTags.push(tag);
                    
                    const tagElement = document.createElement('div');
                    tagElement.className = 'tag';
                    tagElement.innerHTML = `
                        ${tag}
                        <span class="tag-remove" data-tag="${tag}">
                            <i class="fa fa-times"></i>
                        </span>
                    `;
                    
                    tagsContainer.appendChild(tagElement);
                    
                    // 绑定移除标签事件
                    tagElement.querySelector('.tag-remove').addEventListener('click', function() {
                        const tagToRemove = this.getAttribute('data-tag');
                        currentTags = currentTags.filter(t => t !== tagToRemove);
                        tagElement.remove();
                    });
                }
            });
            
            tagInput.value = '';
        }
        
        // 添加季
        function addSeason(seasonData = null) {
            const seasonIndex = document.querySelectorAll('.season-card').length + 1;
            
            const seasonCard = document.createElement('div');
            seasonCard.className = 'season-card';
            
            // 获取主标题用于生成默认图片名
            const mainTitle = document.querySelector('input[name="title"]')?.value || '';
            const defaultImageName = mainTitle ? 
                `${mainTitle.replace(/\s+/g, '_').toLowerCase()}_s${seasonIndex}` : '';
            
            // 季卡片内容（支持回填数据）
            seasonCard.innerHTML = `
                <span class="remove-season">
                    <i class="fa fa-times"></i>
                </span>
                <h3 class="font-medium text-gray-700 mb-2">第 ${seasonIndex} 季</h3>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">季标题</label>
                        <input type="text" name="season-title" 
                            value="${seasonData?.title || ''}"
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                            placeholder="例如：第一季">
                    </div>
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">季数</label>
                        <input type="number" name="season-number" 
                            value="${seasonData?.season || seasonIndex}"
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">集数</label>
                        <input type="text" name="episodes" 
                            value="${seasonData?.episodes || ''}"
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                            placeholder="例如：12 或 '剧场版'">
                    </div>
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">播出时间</label>
                        <input type="text" name="airing" 
                            value="${seasonData?.airing || ''}"
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                            placeholder="例如：2020 或 2020-2021">
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">季状态</label>
                        <select name="season-status" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="已看完" ${seasonData?.status === '已看完' ? 'selected' : ''}>已看完</option>
                            <option value="部分观看" ${seasonData?.status === '部分观看' ? 'selected' : ''}>部分观看</option>
                            <option value="未看" ${seasonData?.status === '未看' ? 'selected' : ''}>未看</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">季评分</label>
                        <input type="number" name="season-star" min="0" max="5" step="0.1" 
                            value="${seasonData?.star || 0}"
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>
                
                <div class="mb-3">
                    <label class="block text-sm text-gray-600 mb-1">季图片路径</label>
                    <div class="image-input-group">
                        <input type="text" name="season-image" 
                            value="${seasonData ? seasonData.image.replace('./images/', '').split('.')[0] : defaultImageName}"
                            class="px-3 py-2 border border-gray-300 rounded-l-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                            placeholder="输入图片文件名（不含路径和扩展名）">
                        <select name="season-image-format" class="px-3 py-2 border border-gray-300 rounded-r-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="webp" ${seasonData?.image?.endsWith('webp') ? 'selected' : ''}>webp</option>
                            <option value="jpg" ${seasonData?.image?.endsWith('jpg') ? 'selected' : ''}>jpg</option>
                            <option value="png" ${seasonData?.image?.endsWith('png') ? 'selected' : ''}>png</option>
                            <option value="jpeg" ${seasonData?.image?.endsWith('jpeg') ? 'selected' : ''}>jpeg</option>
                            <option value="gif" ${seasonData?.image?.endsWith('gif') ? 'selected' : ''}>gif</option>
                        </select>
                    </div>
                    <p class="text-xs text-gray-500 mt-1">实际路径为：./images/文件名.扩展名</p>
                </div>
                
                <div class="mb-3">
                    <label class="block text-sm text-gray-600 mb-1">剧情简介</label>
                    <textarea name="description" rows="3" 
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">${seasonData?.description || ''}</textarea>
                    <div class="mt-1 flex justify-end">
                        <button type="button" class="format-description-btn text-xs bg-gray-200 hover:bg-gray-300 text-gray-700 px-2 py-1 rounded">
                            <i class="fa fa-magic mr-1"></i>格式化文本
                        </button>
                    </div>
                </div>
            `;
            
            seasonsContainer.appendChild(seasonCard);
            
            // 绑定移除季事件
            seasonCard.querySelector('.remove-season').addEventListener('click', function() {
                if (document.querySelectorAll('.season-card').length > 1) {
                    seasonCard.remove();
                    // 重新编号季标题
                    document.querySelectorAll('.season-card').forEach((card, index) => {
                        card.querySelector('h3').textContent = `第 ${index + 1} 季`;
                        card.querySelector('input[name="season-number"]').value = index + 1;
                    });
                }
            });
        }
        
        // 保存动漫
        function saveAnime() {
            const formData = new FormData(animeForm);
            const formObject = Object.fromEntries(formData.entries());
            const animeId = parseInt(formObject.id);
            
            // 处理主图片路径
            const mainImageName = formObject.image || formObject.title.replace(/\s+/g, '_').toLowerCase();
            const fullImagePath = `./images/${mainImageName}.${formObject['image-format']}`;
            
            // 处理季信息
            const seasons = [];
            document.querySelectorAll('.season-card').forEach(card => {
                const seasonImageName = card.querySelector('input[name="season-image"]').value || 
                                      `${formObject.title.replace(/\s+/g, '_').toLowerCase()}_s${card.querySelector('input[name="season-number"]').value}`;
                const fullSeasonImagePath = `./images/${seasonImageName}.${card.querySelector('select[name="season-image-format"]').value}`;
                
                // 处理剧情简介，如果为空则使用默认值
                let description = card.querySelector('textarea[name="description"]').value;
                if (!description.trim()) {
                    description = '暂未播出';
                }
                
                const seasonData = {
                    season: parseInt(card.querySelector('input[name="season-number"]').value),
                    title: card.querySelector('input[name="season-title"]').value,
                    episodes: card.querySelector('input[name="episodes"]').value,
                    airing: card.querySelector('input[name="airing"]').value,
                    status: card.querySelector('select[name="season-status"]').value,
                    star: parseFloat(card.querySelector('input[name="season-star"]').value) || 0,
                    image: fullSeasonImagePath,
                    // 将换行符转换为<br>标签
                    description: description.replace(/\n/g, '<br>')
                };
                seasons.push(seasonData);
            });
            
            // 创建动漫对象
            const anime = {
                id: animeId,
                title: formObject.title,
                image: fullImagePath,
                tags: [...currentTags],
                status: formObject.status,
                star: parseFloat(formObject.star) || 0,
                seasons: seasons,
                director: formObject.director,
                favorite: formObject.favorite === 'on'
            };
            
            // 检查是新增还是编辑（通过ID是否已存在）
            if (currentEditIndex !== -1) {
                // 编辑模式：替换现有数据
                animeData[currentEditIndex] = anime;
                currentEditIndex = -1;
                showNotification('动漫数据已更新！', 'success');
            } else {
                // 新增模式：添加到数组
                animeData.push(anime);
                showNotification('动漫已成功添加！', 'success');
            }
            
            // 重置表单
            resetForm();
            
            // 更新UI
            updateJsonPreview();
            updateAnimeList();
        }
        
        // 重置表单
        function resetForm() {
            animeForm.reset();
            currentTags = [];
            currentEditIndex = -1; // 重置编辑索引
            tagsContainer.innerHTML = '';
            seasonsContainer.innerHTML = '';
            addSeason();
            setAutoIncrementId(); // 重置ID为新的自增值
        }
        
        // 更新JSON预览
        function updateJsonPreview() {
            jsonPreview.textContent = JSON.stringify(animeData, null, 2);
        }
        
        // 更新动漫列表（带分页和搜索）
        function updateAnimeList() {
            // 1. 先进行搜索过滤
            let filteredData = [...animeData];
            
            if (searchTerm) {
                const searchLower = searchTerm.toLowerCase();
                filteredData = filteredData.filter(anime => {
                    // 检查是否匹配ID或标题
                    const matchesId = anime.id.toString() === searchLower;
                    const matchesTitle = anime.title.toLowerCase().includes(searchLower);
                    return matchesId || matchesTitle;
                });
            }
            
            // 2. 计算分页信息
            const totalItems = filteredData.length;
            const totalPages = Math.ceil(totalItems / itemsPerPage);
            const startIndex = (currentPage - 1) * itemsPerPage;
            const endIndex = startIndex + itemsPerPage;
            const currentItems = filteredData.slice(startIndex, endIndex);
            
            // 3. 渲染当前页数据
            animeList.innerHTML = '';
            
            if (currentItems.length === 0) {
                animeList.innerHTML = '<p class="text-gray-500 text-center py-4">暂无匹配的动漫数据</p>';
            } else {
                currentItems.forEach((anime, indexInPage) => {
                    // 计算在原始数据中的索引
                    const originalIndex = filteredData.findIndex(item => item.id === anime.id);
                    
                    const animeElement = document.createElement('div');
                    animeElement.className = 'border border-gray-200 rounded-lg p-4';
                    animeElement.innerHTML = `
                        <div class="flex justify-between items-start">
                            <div>
                                <h3 class="font-medium text-gray-800">${anime.title}</h3>
                                <p class="text-sm text-gray-600">ID: ${anime.id} | 导演: ${anime.director || '未知'} | 评分: ${anime.star}</p>
                                <div class="mt-1 flex flex-wrap">
                                    ${anime.tags.map(tag => `
                                        <span class="bg-gray-100 text-gray-800 text-xs px-2 py-1 rounded-full mr-1 mb-1">${tag}</span>
                                    `).join('')}
                                </div>
                            </div>
                            <div class="flex space-x-2">
                                <button class="edit-anime text-blue-500 hover:text-blue-700" data-index="${originalIndex}">
                                    <i class="fa fa-edit"></i>
                                </button>
                                <button class="delete-anime text-red-500 hover:text-red-700" data-index="${originalIndex}">
                                    <i class="fa fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    `;
                    
                    animeList.appendChild(animeElement);
                    
                    // 绑定编辑和删除事件
                    animeElement.querySelector('.edit-anime').addEventListener('click', function() {
                        editAnimeByID(anime.id); // 使用ID
                    });
                    
                    animeElement.querySelector('.delete-anime').addEventListener('click', function() {
                        deleteAnimeByID(anime.id); 
                    });
                });
            }
            
            // 4. 渲染分页控件
            renderPagination(totalPages);
        }
        
		// 通过ID查找动漫索引的函数
		function findAnimeIndexByID(id) {
		    return animeData.findIndex(item => item.id === id);
		}
		// 编辑函数
		function editAnimeByID(id) {
		    const index = findAnimeIndexByID(id);
		    if (index !== -1) {
		        editAnime(index);
		    }
		}
		
		// 修改删除函数
		function deleteAnimeByID(id) {
		    const index = findAnimeIndexByID(id);
		    if (index !== -1) {
		        deleteAnime(index);
		    }
		}
		
        // 渲染分页控件
        function renderPagination(totalPages) {
            paginationContainer.innerHTML = '';
            
            // 只有一页或无数据时不显示分页
            if (totalPages <= 1) {
                return;
            }
            
            // 上一页按钮
            const prevBtn = document.createElement('button');
            prevBtn.innerHTML = '<i class="fa fa-chevron-left"></i>';
            prevBtn.disabled = currentPage === 1;
            prevBtn.addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage--;
                    updateAnimeList();
                }
            });
            paginationContainer.appendChild(prevBtn);
            
            // 页码按钮（最多显示10个页码）
            let startPage = Math.max(1, currentPage - 2);
            let endPage = Math.min(totalPages, startPage + 9);
            
            // 如果后面页数不足，向前调整
            if (endPage - startPage < 4 && startPage > 1) {
                startPage = Math.max(1, endPage - 4);
            }
            
            for (let i = startPage; i <= endPage; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.textContent = i;
                if (i === currentPage) {
                    pageBtn.classList.add('active');
                }
                pageBtn.addEventListener('click', () => {
                    currentPage = i;
                    updateAnimeList();
                });
                paginationContainer.appendChild(pageBtn);
            }
            
            // 下一页按钮
            const nextBtn = document.createElement('button');
            nextBtn.innerHTML = '<i class="fa fa-chevron-right"></i>';
            nextBtn.disabled = currentPage === totalPages;
            nextBtn.addEventListener('click', () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    updateAnimeList();
                }
            });
            paginationContainer.appendChild(nextBtn);
        }
        
        // 编辑动漫
        function editAnime(index) {
            currentEditIndex = index; // 记录当前编辑的索引
            const anime = animeData[index];
            
            // 填充表单
            document.querySelector('input[name="id"]').value = anime.id;
            document.querySelector('input[name="title"]').value = anime.title;
            
            // 解析图片路径，提取文件名和格式
            const imagePathParts = anime.image.replace('./images/', '').split('.');
            const imageFormat = imagePathParts.pop();
            const imageName = imagePathParts.join('.');
            document.querySelector('input[name="image"]').value = imageName;
            document.querySelector('select[name="image-format"]').value = imageFormat;
            
            document.querySelector('select[name="status"]').value = anime.status;
            document.querySelector('input[name="star"]').value = anime.star;
            document.querySelector('input[name="director"]').value = anime.director || '';
            document.querySelector('input[name="favorite"]').checked = anime.favorite;
            
            // 填充标签
            currentTags = [...anime.tags];
            tagsContainer.innerHTML = '';
            currentTags.forEach(tag => {
                const tagElement = document.createElement('div');
                tagElement.className = 'tag';
                tagElement.innerHTML = `
                    ${tag}
                    <span class="tag-remove" data-tag="${tag}">
                        <i class="fa fa-times"></i>
                    </span>
                `;
                tagsContainer.appendChild(tagElement);
                
                // 绑定移除标签事件
                tagElement.querySelector('.tag-remove').addEventListener('click', function() {
                    const tagToRemove = this.getAttribute('data-tag');
                    currentTags = currentTags.filter(t => t !== tagToRemove);
                    tagElement.remove();
                });
            });
            
            // 填充季信息
            seasonsContainer.innerHTML = '';
            anime.seasons.forEach(season => {
                addSeason(season); // 传入季数据进行回填
            });
            
            // 滚动到顶部
            window.scrollTo(0, 0);
            
            // 显示通知
            showNotification('动漫数据已加载到表单中，编辑后将更新原数据', 'success');
        }
        
		// 格式化文本按钮事件
		document.addEventListener('click', function(e) {
		    if (e.target.classList.contains('format-description-btn') || 
		        e.target.closest('.format-description-btn')) {
		        const btn = e.target.classList.contains('format-description-btn') ? 
		                   e.target : e.target.closest('.format-description-btn');
		        const textarea = btn.closest('.mb-3').querySelector('textarea[name="description"]');
		        
		        // 删除多余空行并保留单行换行
		        let text = textarea.value;
		        // 将多个连续换行替换为单个换行
		        text = text.replace(/(\r\n|\r|\n){2,}/g, '\n');
		        // 删除行首行尾空白
		        text = text.split('\n').map(line => line.trim()).join('\n');
		        textarea.value = text;
		        
		        showNotification('文本已格式化，多余空行已删除', 'success');
		    }
		});
		
        // 删除动漫
        function deleteAnime(index) {
            if (confirm('确定要删除这个动漫吗？')) {
                animeData.splice(index, 1);
                
                // 如果删除后当前页没有数据，且不是第一页，则回退一页
                const filteredData = getFilteredData();
                if (filteredData.length > 0 && 
                    Math.ceil(filteredData.length / itemsPerPage) < currentPage) {
                    currentPage--;
                }
                
                updateJsonPreview();
                updateAnimeList();
                showNotification('动漫已删除', 'success');
            }
        }
        
        // 获取过滤后的数据（用于删除后调整分页）
        function getFilteredData() {
            if (!searchTerm) return [...animeData];
            
            const searchLower = searchTerm.toLowerCase();
            return animeData.filter(anime => {
                const matchesId = anime.id.toString() === searchLower;
                const matchesTitle = anime.title.toLowerCase().includes(searchLower);
                return matchesId || matchesTitle;
            });
        }
        
        // 复制JSON到剪贴板
        function copyJsonToClipboard() {
            navigator.clipboard.writeText(JSON.stringify(animeData, null, 2))
                .then(() => {
                    showNotification('JSON已复制到剪贴板', 'success');
                })
                .catch(err => {
                    showNotification('复制失败: ' + err, 'error');
                });
        }
        
        // 保存到本地存储
        function saveToLocalStorage() {
            try {
                localStorage.setItem('animeData', JSON.stringify(animeData));
                showNotification('数据已保存到本地存储', 'success');
            } catch (err) {
                showNotification('保存失败: ' + err, 'error');
            }
        }
        
        // 从本地存储加载
        function loadFromLocalStorage() {
            try {
                const savedData = localStorage.getItem('animeData');
                if (savedData) {
                    animeData = JSON.parse(savedData);
                    updateJsonPreview();
                    updateAnimeList();
                }
            } catch (err) {
                console.error('加载本地存储数据失败:', err);
            }
        }
        
        // 导出JSON
        function exportJson() {
            const dataStr = JSON.stringify(animeData, null, 2);
            const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
            
            const exportFileDefaultName = 'anime-data.json';
            
            const linkElement = document.createElement('a');
            linkElement.setAttribute('href', dataUri);
            linkElement.setAttribute('download', exportFileDefaultName);
            linkElement.click();
            
            showNotification('JSON文件已导出', 'success');
        }
        
        // 导入JSON
        function importJson(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const importedData = JSON.parse(e.target.result);
                    if (Array.isArray(importedData)) {
                        animeData = importedData;
                        currentPage = 1; // 导入后重置分页
                        updateJsonPreview();
                        updateAnimeList();
                        setAutoIncrementId(); // 导入后更新自增ID
                        showNotification('JSON文件已成功导入', 'success');
                    } else {
                        showNotification('导入的文件格式不正确', 'error');
                    }
                } catch (err) {
                    showNotification('导入失败: ' + err, 'error');
                }
            };
            reader.readAsText(file);
            
            // 重置文件输入
            event.target.value = '';
        }
        
        // 清除数据
        function clearData() {
            if (confirm('确定要清除所有数据吗？此操作不可撤销。')) {
                animeData = [];
                currentPage = 1; // 清除数据后重置分页
                resetForm();
                updateJsonPreview();
                updateAnimeList();
                localStorage.removeItem('animeData');
                showNotification('所有数据已清除', 'success');
            }
        }
        
        // 显示通知
        function showNotification(message, type) {
            notification.textContent = message;
            notification.className = `notification ${type} show`;
            
            setTimeout(() => {
                notification.className = 'notification';
            }, 3000);
        }
    </script>
</body>
</html>